package com.yijinsuo.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.lzy.okhttputils.model.HttpParams;
import com.yijinsuo.R;
import com.yijinsuo.base.BaseActivity;
import com.yijinsuo.entity.LoaginResult;
import com.yijinsuo.http.HttpCallBack;
import com.yijinsuo.http.HttpUtils;
import com.yijinsuo.mian.Config;
import com.yijinsuo.mian.MainActivity;
import com.yijinsuo.presenter.LoginPresenterCompl;
import com.yijinsuo.tool.CodeUtils;
import com.yijinsuo.tool.SharedPreferencesUtils;
import com.yijinsuo.tool.VibratorUtil;
import com.yijinsuo.util.DES;
import com.yijinsuo.view.ClearEditText;
import com.yijinsuo.view.TitleBar;

import org.json.JSONObject;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 登录
 */
public class LoginActivity extends BaseActivity {
    private final static String TAG = "LoginActivity";
    @Bind(R.id.titlebar)
    TitleBar titlebar;
    @Bind(R.id.et_phone)
    ClearEditText etPhone;
    @Bind(R.id.et_password)
    ClearEditText etPassword;
    @Bind(R.id.et_code)
    ClearEditText etCode;
    @Bind(R.id.iv_code)
    //
            ImageView ivCode;   //生成验证码
    private String codeStr;
    private CodeUtils codeUtils;
    //
    private int flag;  //标识首页面从哪里进入登录页面
    //
    private LoginPresenterCompl loginPresenterCompl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initTitle() {
        //
        flag = getIntent().getIntExtra("flag", 0);
        //
        codeUtils = CodeUtils.getInstance();
        titlebar.setTitleBar(R.mipmap.back, "登录", 0);
        titlebar.setTitleBarBackgroundColor(ContextCompat.getColor(this,R.color.white));
        titlebar.setTitleBarRightText("注册新用户");
        titlebar.setTitleBarTextColor(ContextCompat.getColor(this,R.color.dan_hong_5));
        titlebar.setTitlebarRightTextColor(ContextCompat.getColor(this,R.color.blue_2));
        //记住账号
        String userAccount = (String) mpreferencesUtils.get(LoginActivity.this, "userAccount", "");
        if (null != userAccount || !userAccount.equals("")) {
            etPhone.setText(userAccount);
        }
    }

    @Override
    protected void initView() {
        Bitmap bitmap = codeUtils.createBitmap();
        ivCode.setImageBitmap(bitmap);
    }

    @Override
    protected void setData() {

    }


    @OnClick({R.id.tv_login, R.id.titlebar_right_text, R.id.titlebar_iv_back, R.id.iv_code, R.id.tv_forget_password})
    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.titlebar_iv_back:
                if (flag == 110) {
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    finish();
                }
//                if(flag==100){
//                    Intent intent=new Intent();
//                    setResult(100,intent);
//                    finish();
//                }
                //正常返回退出
                finish();
                break;
            case R.id.tv_forget_password:    // 忘记密码
                startActivity(new Intent(LoginActivity.this, ForgetPasswordActivity.class));
                break;

            case R.id.iv_code:    // 切换验证码
                ivCode.setImageBitmap(codeUtils.createBitmap());
                break;

            case R.id.titlebar_right_text:
                startActivity(new Intent(LoginActivity.this, RegisteredSecondActivity.class));
                break;

            case R.id.tv_login:
                //做业务逻辑处理
                long[] pattern = {100, 400, 100, 400};
                String phone = etPhone.getText().toString().trim();
                String password = etPassword.getText().toString().trim();
                String et_code = etCode.getText().toString().trim();
                //获取图形验证码
                codeStr = codeUtils.getCode();
                //处理业务逻辑
                if (TextUtils.isEmpty(phone)) {
                    etPhone.setShakeAnimation();
                    VibratorUtil.Vibrate(context, pattern, false);
                    Toast.makeText(activity, "请输入手机号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(password)) {
                    etPassword.setShakeAnimation();
                    VibratorUtil.Vibrate(context, pattern, false);
                    Toast.makeText(activity, "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(et_code)) {
                    etCode.setShakeAnimation();
                    VibratorUtil.Vibrate(context, pattern, false);
                    Toast.makeText(activity, "请输入验证码", Toast.LENGTH_SHORT).show();
                    return;

                }
                if (!codeStr.equals(et_code)) {
                    VibratorUtil.Vibrate(context, pattern, false);
                    etCode.setShakeAnimation();
                    Toast.makeText(activity, "验证码输入错误", Toast.LENGTH_SHORT).show();
                    return;

                } else {
                    try {
                        HttpParams params = new HttpParams();
                        params.put("userAccount", phone);
                        params.put("userPassword", DES.encryptDES(password, Config.DES_KEY));
                        HttpUtils.post(Config.LOGIN, params, new HttpCallBack(activity, "登录中...") {
                            @Override
                            public void onSucceed(JSONObject result, String code, String message) {
                                // 登录成功
                                Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
                                SharedPreferencesUtils.getInstance().put(context, "userAccount", etPhone.getText().toString().trim());
                                if (null != result) {
                                    try {
                                        LoaginResult login = new LoaginResult(new JSONObject(result.toString()));
                                        mpreferencesUtils.put(LoginActivity.this, "token", login.getToken());
                                        mpreferencesUtils.put(LoginActivity.this, "jsessionid", login.getJSESSIONID());

                                        //
                                        //在已经登录成功 的情况下退出登录,就回到主页面
                                        if (flag == 110) {
                                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                            finish();
                                            return;
                                        } else if (flag == 100) {  //
                                            Intent intent = new Intent();
                                            setResult(110, intent);
                                            finish();
                                            return;
                                        } else {
                                            finish();
                                        }

                                    } catch (org.json.JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }

                            @Override
                            public void onError(String code, String message) {
                                Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
                            }
                        });

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }


            default:
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (event.getAction() == KeyEvent.KEYCODE_BACK) {
//            if (flag == 110) {
//                startActivity(new Intent(LoginActivity.this, MainActivity.class));
//                finish();
//            }
//        }
        return super.onKeyDown(keyCode, event);
    }

//    @Override
//    public boolean dispatchKeyEvent(KeyEvent event) {
//        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {//点击的是返回键
//            if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {//按键的按下事件
//                Toast.makeText(getApplicationContext(), "dispatchKeyEvent--Down", Toast.LENGTH_SHORT).show();
////               return false;
//            } else if (event.getAction() == KeyEvent.ACTION_UP && event.getRepeatCount() == 0) {//按键的抬起事件
//                Toast.makeText(getApplicationContext(), "dispatchKeyEvent--UP", Toast.LENGTH_SHORT).show();
////               return false;
//            }
//        }
//        return super.dispatchKeyEvent(event);
//    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (flag == 110) {
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            finish();
        }
    }

//    @Override
//    protected int setStatusBarColor() {
//        return ContextCompat.getColor(this, R.color.white);
//    }
}
